JavaScript Control Flow

Visualizing `return`, `break`, `continue`, `throw`, `if...else`, `switch`, and `try...catch`.

Conditional Statements

Statements that allow different code blocks to run based on conditions.

if (status === 'admin') {
  // code for admin
} else {
  // code for user
}

switch (day) {
  case 'Mon': // ...
  default: // ...
}

Choose a day of the week to see the result of a `switch` statement.


Loop Control (`break` & `continue`)

Statements that alter the flow of a loop. `continue` skips the current iteration, and `break` exits the loop entirely.

for (let i = 0; i < 10; i++) {
  if (i === 3) continue; // Skips 3
  if (i === 7) break;    // Exits loop
  console.log(i);
}

The loop runs from 0 to 9. The loop will `continue` when `i` is 3, and `break` when `i` is 7.


Error Handling (`throw`, `try...catch`)

`try...catch` allows you to handle errors gracefully. The `try` block contains code that might throw an error. If an error is thrown, execution jumps to the `catch` block. The `throw` statement creates a custom error.

function checkAge(age) {
  if (age < 18) {
    throw new Error("Must be 18+");
  }
}
try {
  checkAge(15);
} catch (e) {
  console.error(e.message);
}

Enter an age to see if a custom error is thrown and caught.


Function Termination (`return`)

The `return` statement ends function execution and specifies a value to be returned to the function caller. It immediately terminates the function, ignoring any code that follows it.

function multiply(a, b) {
  if (a > 10) {
    return "Too large";
  }
  return a * b;
}

See how the `return` statement affects the function's output.

Result of `multiply(5, 10)`:

Result of `multiply(15, 10)`: